package org.third.security.crypto;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.InvalidKeySpecException;

public class Pbkdf2Test {
    public static byte[] getDeriveKey(byte[] salt, char[] password, int dkLengthBytes, String jceProvider, int pbkdf2Iterations) {
        String pbkdf2WithHmacSHA256 = "PBKDF2WithHmacSHA256";
        return pbkdf2(salt, password, dkLengthBytes, pbkdf2Iterations, pbkdf2WithHmacSHA256, jceProvider);
    }

    public static byte[] pbkdf2(byte[] salt, char[] password, int dkLengthBytes, int pbkdf2Iterations, String pbkdf2WithHmacSHA256,
            String jceProvider) {
        byte[] derivedKey;
        try {
            PBEKeySpec spec = new PBEKeySpec(password, salt, pbkdf2Iterations, dkLengthBytes * 8);
            SecretKeyFactory skf = SecretKeyFactory.getInstance(pbkdf2WithHmacSHA256, jceProvider);
            derivedKey = skf.generateSecret(spec).getEncoded();
        } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
        return derivedKey;
    }
}
